package com.free.space.common;

import com.alibaba.fastjson.JSONObject;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

/**
 * Created by zhulj on 2019/3/26.
 */
public class CommonGetParameter {
    /**
     * 获取 json 参数
     * @param request
     * @return
     * @throws IOException
     */
    public JSONObject getParameter(HttpServletRequest request) throws IOException {
        //设置请求字符集
        request.setCharacterEncoding("utf-8");
        StringBuilder reqStr = new StringBuilder(256);
        ByteArrayOutputStream bainput = new ByteArrayOutputStream();
        byte[] bt = new byte[256];
        InputStream input = request.getInputStream();
        int len = input.read(bt);
        //循环获取请求数据
        while (len != -1) {
            bainput.write(bt, 0, len);
            len = input.read(bt);
        }
        reqStr.append(new String(bainput.toByteArray()));
        IOUtils.closeQuietly(input);
        JSONObject json = JSONObject.parseObject(reqStr.toString());
        return json;
    }
}
